<template>
  <div class="add-bom-page">
    <!-- 页面标题和返回按钮 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          @click="goBack" 
          type="text" 
          class="back-button"
          icon="ArrowLeft"
        >
          返回
        </el-button>
        <h1 class="page-title">新增BOM</h1>
      </div>
    </div>

    <!-- 可滚动的内容区域 -->
    <div class="scrollable-content">
      <!-- 基础信息表单 -->
      <div class="form-container">
        <div class="form-card">
          <div class="card-header">
            <span class="card-title">基础信息</span>
          </div>
          
          <div class="form-content">
            <el-form 
              :model="bomForm" 
              :rules="formRules" 
              ref="bomFormRef" 
              label-width="120px"
              class="bom-form"
            >
              <el-row :gutter="24">
                <!-- 左列 -->
                <el-col :span="12">
                  <el-form-item label="BOM编号" prop="bomNumber" required>
                    <el-input 
                      v-model="bomForm.bomNumber" 
                      placeholder="BOM编号"
                      readonly
                      class="bom-number-input"
                    >
                      <template #append>
                        <el-checkbox v-model="bomForm.isSystemNumber" label="系统编号" />
                      </template>
                    </el-input>
                  </el-form-item>

                  <el-form-item label="默认BOM" prop="isDefaultBom" required>
                    <el-checkbox v-model="bomForm.isDefaultBom" />
                  </el-form-item>

                  <el-form-item label="成品类型" prop="finishedProductType" required>
                    <el-select 
                      v-model="bomForm.finishedProductType" 
                      placeholder="请选择成品类型"
                      class="full-width"
                    >
                      <el-option label="成品" value="成品" />
                      <el-option label="半成品" value="半成品" />
                      <el-option label="其他" value="其他" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="日产量" prop="dailyOutput">
                    <el-input 
                      v-model="bomForm.dailyOutput" 
                      placeholder="请输入日产量"
                      class="full-width"
                    />
                  </el-form-item>

                  <el-form-item label="备注" prop="remarks">
                    <el-input 
                      v-model="bomForm.remarks" 
                      type="textarea" 
                      :rows="3"
                      placeholder="请输入备注"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>

                <!-- 右列 -->
                <el-col :span="12">
                  <el-form-item label="BOM主题" prop="bomSubject" required>
                    <el-input 
                      v-model="bomForm.bomSubject" 
                      placeholder="请输入BOM主题"
                      class="full-width"
                    />
                  </el-form-item>

                  <el-form-item label="版本" prop="version" required>
                    <el-input 
                      v-model="bomForm.version" 
                      placeholder="请输入版本"
                      class="full-width"
                    />
                  </el-form-item>

                  <el-form-item label="成品名称" prop="finishedProductName" required>
                    <el-input 
                      v-model="bomForm.finishedProductName" 
                      placeholder="请选择物品"
                      class="full-width"
                      readonly
                    >
                      <template #suffix>
                        <el-icon class="item-selector-icon" @click="openItemSelector">
                          <Box />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </div>

      <!-- BOM配件部分 -->
      <div class="form-container">
        <div class="form-card">
          <div class="card-header">
            <span class="card-title">BOM配件</span>
            <div class="card-actions">
              <el-button type="primary" size="small" @click="addBomComponent">
                <el-icon><Plus /></el-icon>
                添加
              </el-button>
              <el-button type="warning" size="small" @click="removeBomComponent" :disabled="!selectedBomComponents.length">
                <el-icon><Delete /></el-icon>
                移除
              </el-button>
            </div>
          </div>
          
          <div class="table-content">
            <el-table 
              :data="bomComponents" 
              @selection-change="handleBomComponentSelectionChange"
              border
              stripe
              class="bom-table"
              empty-text="暂无数据"
              :min-height="200"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="serialNumber" label="序号" width="80" />
              <el-table-column prop="itemNumber" label="物品编号" width="150" />
              <el-table-column prop="itemName" label="物品名称" min-width="150" />
              <el-table-column prop="specification" label="规格型号" width="120" />
              <el-table-column prop="unit" label="单位" width="80" />
              <el-table-column prop="brand" label="品牌" width="100" />
              <el-table-column prop="quantity" label="*配件数量" width="120">
                <template #default="scope">
                  <el-input 
                    v-model="scope.row.quantity" 
                    type="number" 
                    placeholder="数量"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="lossRate" label="损耗率" width="100">
                <template #default="scope">
                  <el-input 
                    v-model="scope.row.lossRate" 
                    type="number" 
                    placeholder="损耗率"
                    size="small"
                  >
                    <template #append>%</template>
                  </el-input>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 工艺流程部分 -->
      <div class="form-container">
        <div class="form-card">
          <div class="card-header">
            <span class="card-title">工艺流程</span>
            <div class="card-actions">
              <el-button type="primary" size="small" @click="addProcessFlow">
                <el-icon><Plus /></el-icon>
                添加
              </el-button>
              <el-button type="warning" size="small" @click="removeProcessFlow" :disabled="!selectedProcessFlows.length">
                <el-icon><Delete /></el-icon>
                移除
              </el-button>
            </div>
          </div>
          
          <div class="table-content">
            <el-table 
              :data="processFlows" 
              @selection-change="handleProcessFlowSelectionChange"
              border
              stripe
              class="process-table"
              empty-text="暂无数据"
              :min-height="200"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="serialNumber" label="序号" width="80" />
              <el-table-column prop="processCode" label="工序编码" width="120" />
              <el-table-column prop="processName" label="工序名称" min-width="120" />
              <el-table-column prop="processingOrder" label="加工顺序" width="100" />
              <el-table-column prop="processFlow" label="工艺流程" width="120" />
              <el-table-column prop="personInCharge" label="负责人" width="100" />
              <el-table-column prop="department" label="部门" width="100" />
              <el-table-column prop="unitWorkload" label="单位工作量" width="120" />
              <el-table-column prop="remarks" label="备注" min-width="120" />
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="editProcessFlow(scope.row)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 附件部分 -->
      <div class="form-container">
        <div class="form-card">
          <div class="card-header">
            <span class="card-title">附件</span>
          </div>
          
          <div class="attachment-content">
            <div class="attachment-grid">
              <!-- 已上传文件显示区域 -->
              <div class="attachment-display">
                <div v-if="attachments.length > 0" class="attachment-list">
                  <div 
                    v-for="(attachment, index) in attachments" 
                    :key="index" 
                    class="attachment-item"
                  >
                    <div class="attachment-info">
                      <div class="file-name">{{ attachment.fileName }}</div>
                      <div class="file-details">
                        <span>文件大小: {{ formatFileSize(attachment.fileSize) }}</span>
                        <span>上传日期: {{ attachment.uploadDate }}</span>
                      </div>
                    </div>
                    <div class="attachment-actions">
                      <el-button type="text" size="small" @click="reuploadFile(attachment)">重新上传</el-button>
                      <el-button type="text" size="small" @click="deleteFile(attachment, index)" class="delete-btn">删除</el-button>
                    </div>
                  </div>
                </div>
                <div v-else class="empty-attachments">
                  <el-icon class="empty-icon"><Document /></el-icon>
                  <span>暂无附件</span>
                </div>
              </div>
              
              <!-- 文件上传区域 -->
              <div class="upload-zone">
                <el-upload
                  ref="uploadRef"
                  :action="uploadAction"
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :on-remove="handleFileRemove"
                  :file-list="fileList"
                  drag
                  multiple
                  class="upload-area"
                >
                  <el-icon class="upload-icon"><Upload /></el-icon>
                  <div class="upload-text">
                    <span>点击上传 / 拖拽到此区域</span>
                  </div>
                </el-upload>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 物品选择对话框 -->
    <el-dialog 
      v-model="itemSelectorVisible" 
      title="选择物品" 
      width="80%" 
      :close-on-click-modal="false"
      class="item-selector-dialog"
    >
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="itemSearchForm.keyword" 
              placeholder="请输入物品编号/名称/规格型号"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="itemSearchForm.category" placeholder="请选择物品类别" clearable>
              <el-option label="原材料" value="原材料" />
              <el-option label="半成品" value="半成品" />
              <el-option label="成品" value="成品" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="itemSearchForm.classification" placeholder="请选择物品分类" clearable>
              <el-option label="金属" value="金属" />
              <el-option label="塑料" value="塑料" />
              <el-option label="木材" value="木材" />
              <el-option label="电子" value="电子" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="itemSearchForm.inventoryStatus" placeholder="库存状态" clearable>
              <el-option label="有库存" value="有库存" />
              <el-option label="无库存" value="无库存" />
              <el-option label="库存不足" value="库存不足" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="searchItems">查询</el-button>
            <el-button @click="resetItemSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 物品列表表格 -->
      <div class="table-section">
        <el-table 
          :data="itemList" 
          @current-change="handleItemCurrentChange"
          @selection-change="handleItemSelectionChange"
          border
          stripe
          height="400"
          class="item-table"
          highlight-current-row
          empty-text="暂无数据"
        >
          <el-table-column type="radio" width="55">
            <template #default="scope">
              <el-radio 
                v-model="selectedItemId" 
                :label="scope.row.itemNumber"
                @change="handleRadioChange(scope.row)"
              >
                &nbsp;
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="serialNumber" label="序号" width="80" />
          <el-table-column prop="itemNumber" label="物品编号" width="150" />
          <el-table-column prop="itemName" label="物品名称" min-width="150" />
          <el-table-column prop="specification" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="category" label="物品类别" width="120" />
          <el-table-column prop="classification" label="物品分类" width="120" />
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">
          共 {{ totalItems }} 项数据
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="totalItems"
          layout="sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeItemSelector">取消</el-button>
          <el-button type="primary" @click="confirmItemSelection" :disabled="!selectedItemId">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- BOM配件选择对话框 -->
    <el-dialog 
      v-model="bomComponentSelectorVisible" 
      title="选择BOM配件" 
      width="80%" 
      :close-on-click-modal="false"
      class="bom-component-selector-dialog"
    >
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="bomComponentSearchForm.keyword" 
              placeholder="请输入物品编号/名称/规格型号"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="bomComponentSearchForm.category" placeholder="请选择物品类别" clearable>
              <el-option label="原材料" value="原材料" />
              <el-option label="半成品" value="半成品" />
              <el-option label="成品" value="成品" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="bomComponentSearchForm.classification" placeholder="请选择物品分类" clearable>
              <el-option label="金属" value="金属" />
              <el-option label="塑料" value="塑料" />
              <el-option label="木材" value="木材" />
              <el-option label="电子" value="电子" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="bomComponentSearchForm.inventoryStatus" placeholder="库存状态" clearable>
              <el-option label="有库存" value="有库存" />
              <el-option label="无库存" value="无库存" />
              <el-option label="库存不足" value="库存不足" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="searchBomComponents">查询</el-button>
            <el-button @click="resetBomComponentSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 物品列表表格 -->
      <div class="table-section">
        <el-table 
          :data="bomComponentItemList" 
          @selection-change="handleBomComponentItemSelectionChange"
          border
          stripe
          height="400"
          class="bom-component-item-table"
          empty-text="暂无数据"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="serialNumber" label="序号" width="80" />
          <el-table-column prop="itemNumber" label="物品编号" width="150" />
          <el-table-column prop="itemName" label="物品名称" min-width="150" />
          <el-table-column prop="specification" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="category" label="物品类别" width="120" />
          <el-table-column prop="classification" label="物品分类" width="120" />
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">
          共 {{ totalBomComponentItems }} 项数据
        </div>
        <el-pagination
          v-model:current-page="bomComponentCurrentPage"
          v-model:page-size="bomComponentPageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="totalBomComponentItems"
          layout="sizes, prev, pager, next"
          @size-change="handleBomComponentSizeChange"
          @current-change="handleBomComponentCurrentChange"
        />
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeBomComponentSelector">取消</el-button>
          <el-button type="primary" @click="confirmBomComponentSelection" :disabled="!selectedBomComponentItems.length">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工艺流程选择对话框 -->
    <el-dialog 
      v-model="processFlowSelectorVisible" 
      title="选择工艺流程" 
      width="80%" 
      :close-on-click-modal="false"
      class="process-flow-selector-dialog"
    >
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="processFlowSearchForm.keyword" 
              placeholder="请输入工艺流程编号/名称"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="processFlowSearchForm.processType" placeholder="请选择工艺类型" clearable>
              <el-option label="新产品工序流程" value="新产品工序流程" />
              <el-option label="标准工序流程" value="标准工序流程" />
              <el-option label="定制工序流程" value="定制工序流程" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="processFlowSearchForm.status" placeholder="状态" clearable>
              <el-option label="启用" value="启用" />
              <el-option label="禁用" value="禁用" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="searchProcessFlows">查询</el-button>
            <el-button @click="resetProcessFlowSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 工艺流程列表表格 -->
      <div class="table-section">
        <el-table 
          :data="processFlowList" 
          @selection-change="handleProcessFlowItemSelectionChange"
          border
          stripe
          height="400"
          class="process-flow-item-table"
          empty-text="暂无数据"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="serialNumber" label="序号" width="80" />
          <el-table-column prop="processFlowNumber" label="工艺流程编号" width="150" />
          <el-table-column prop="processFlowName" label="工艺流程名称" min-width="200" />
          <el-table-column prop="processCount" label="工序数量" width="100" />
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">
          共 {{ totalProcessFlowItems }} 项数据
        </div>
        <el-pagination
          v-model:current-page="processFlowCurrentPage"
          v-model:page-size="processFlowPageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="totalProcessFlowItems"
          layout="sizes, prev, pager, next"
          @size-change="handleProcessFlowSizeChange"
          @current-change="handleProcessFlowCurrentChange"
        />
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeProcessFlowSelector">取消</el-button>
          <el-button type="primary" @click="confirmProcessFlowSelection" :disabled="!selectedProcessFlowItems.length">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 全局操作按钮 -->
    <div class="global-actions">
      <el-button @click="goBack" size="large" class="close-btn">关闭</el-button>
      <el-button type="primary" @click="submitForm" size="large" class="confirm-btn">确定</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Box, ArrowLeft, Plus, Delete, Upload, Document } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 路由实例
const router = useRouter()

// 表单引用
const bomFormRef = ref()

// 表单数据
const bomForm = reactive({
  bomNumber: 'BOM0000814905',
  isSystemNumber: true,
  isDefaultBom: false,
  finishedProductType: '',
  dailyOutput: '',
  remarks: '',
  bomSubject: '',
  version: '',
  finishedProductName: ''
})

// BOM配件数据
const bomComponents = ref([])
const selectedBomComponents = ref([])

// 工艺流程数据
const processFlows = ref([])
const selectedProcessFlows = ref([])

// 附件数据
const attachments = ref([])
const fileList = ref([])
const uploadRef = ref()
const uploadAction = 'https://your-upload-api.com/upload' // 替换为实际的上传API

// 物品选择对话框相关
const itemSelectorVisible = ref(false)
const itemList = ref([])
const totalItems = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedItems = ref([])
const selectedItemId = ref('') // 新增：用于单选模式下选中项的itemNumber

const itemSearchForm = reactive({
  keyword: '',
  category: '',
  classification: '',
  inventoryStatus: ''
})

// BOM配件选择对话框相关
const bomComponentSelectorVisible = ref(false)
const bomComponentItemList = ref([])
const totalBomComponentItems = ref(0)
const bomComponentCurrentPage = ref(1)
const bomComponentPageSize = ref(10)
const selectedBomComponentItems = ref([])
const bomComponentSelectedItemId = ref('') // 新增：用于单选模式下选中项的itemNumber

const bomComponentSearchForm = reactive({
  keyword: '',
  category: '',
  classification: '',
  inventoryStatus: ''
})

// 工艺流程选择对话框相关
const processFlowSelectorVisible = ref(false)
const processFlowList = ref([])
const totalProcessFlowItems = ref(0)
const processFlowCurrentPage = ref(1)
const processFlowPageSize = ref(10)
const selectedProcessFlowItems = ref([])
const processFlowSelectedItemId = ref('') // 新增：用于单选模式下选中项的itemNumber

const processFlowSearchForm = reactive({
  keyword: '',
  processType: '',
  status: ''
})

// 表单验证规则
const formRules = {
  finishedProductType: [
    { required: true, message: '请选择成品类型', trigger: 'change' }
  ],
  bomSubject: [
    { required: true, message: '请输入BOM主题', trigger: 'blur' }
  ],
  version: [
    { required: true, message: '请输入版本', trigger: 'blur' }
  ],
  finishedProductName: [
    { required: true, message: '请选择成品名称', trigger: 'blur' }
  ]
}

// 页面加载时的初始化
onMounted(() => {
  // 可以在这里添加初始化逻辑，比如获取BOM编号等
  initSampleData()
})

// 初始化示例数据
const initSampleData = () => {
  // 添加示例附件
  attachments.value = [
    {
      fileName: '新建文本文档.PDF',
      fileSize: 0,
      uploadDate: '2022-08-1 17:45:27'
    }
  ]
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// BOM配件相关方法
const addBomComponent = () => {
  openBomComponentSelector()
}

const removeBomComponent = () => {
  if (selectedBomComponents.value.length === 0) {
    ElMessage.warning('请选择要移除的配件')
    return
  }
  
  const selectedIds = selectedBomComponents.value.map(item => item.serialNumber)
  bomComponents.value = bomComponents.value.filter(item => !selectedIds.includes(item.serialNumber))
  
  // 重新编号
  bomComponents.value.forEach((item, index) => {
    item.serialNumber = index + 1
  })
  
  selectedBomComponents.value = []
  ElMessage.success('移除成功')
}

const handleBomComponentSelectionChange = (selection) => {
  selectedBomComponents.value = selection
}

// 工艺流程相关方法
const addProcessFlow = () => {
  openProcessFlowSelector()
}

const removeProcessFlow = () => {
  if (selectedProcessFlows.value.length === 0) {
    ElMessage.warning('请选择要移除的工艺流程')
    return
  }
  
  const selectedIds = selectedProcessFlows.value.map(item => item.serialNumber)
  processFlows.value = processFlows.value.filter(item => !selectedIds.includes(item.serialNumber))
  
  // 重新编号
  processFlows.value.forEach((item, index) => {
    item.serialNumber = index + 1
  })
  
  selectedProcessFlows.value = []
  ElMessage.success('移除成功')
}

const handleProcessFlowSelectionChange = (selection) => {
  selectedProcessFlows.value = selection
}

const editProcessFlow = (row) => {
  // 这里可以实现编辑工艺流程的逻辑
  ElMessage.info('编辑功能开发中...')
}

// 附件相关方法
const handleFileChange = (file, fileList) => {
  // 处理文件选择
  console.log('文件选择:', file, fileList)
}

const handleFileRemove = (file, fileList) => {
  // 处理文件移除
  console.log('文件移除:', file, fileList)
}

const reuploadFile = (attachment) => {
  // 重新上传文件
  ElMessage.info('重新上传功能开发中...')
}

const deleteFile = (attachment, index) => {
  ElMessageBox.confirm(
    '确定要删除这个附件吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    attachments.value.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 物品选择对话框相关方法
const openItemSelector = () => {
  itemSelectorVisible.value = true
  searchItems() // 打开对话框时自动搜索
}

const closeItemSelector = () => {
  itemSelectorVisible.value = false
  selectedItems.value = []
  itemSearchForm.keyword = ''
  itemSearchForm.category = ''
  itemSearchForm.classification = ''
  itemSearchForm.inventoryStatus = ''
  selectedItemId.value = '' // 关闭时重置选中项
}

const searchItems = () => {
  // 模拟搜索逻辑
  currentPage.value = 1
  fetchItems()
}

const resetItemSearch = () => {
  itemSearchForm.keyword = ''
  itemSearchForm.category = ''
  itemSearchForm.classification = ''
  itemSearchForm.inventoryStatus = ''
  searchItems()
}

const fetchItems = () => {
  // 模拟后端分页数据
  const mockItems = [
    { serialNumber: 1, itemNumber: 'WPBH001', itemName: '超能胶水', specification: 'GL-1000-TIMEBOND', unit: '个', category: '原材料', classification: '金属' },
    { serialNumber: 2, itemNumber: 'WPBH002', itemName: '神奇螺丝', specification: 'SC-2000-PROBLEMFREE', unit: '个', category: '半成品', classification: '塑料' },
    { serialNumber: 3, itemNumber: 'WPBH004', itemName: '无敌锤子', specification: 'HM-3000-SUCCESS', unit: '个', category: '成品', classification: '木材' },
    { serialNumber: 4, itemNumber: 'WPBH005', itemName: '隐形电线', specification: 'WI-4000-INVISIBLE', unit: '条', category: '原材料', classification: '金属' },
    { serialNumber: 5, itemNumber: 'WPBH003', itemName: '懒人胶带', specification: 'TA-5000-ONESTRIP', unit: '条', category: '半成品', classification: '塑料' },
    { serialNumber: 6, itemNumber: 'WPBH006', itemName: '智能传感器', specification: 'SS-6000-SMART', unit: '个', category: '成品', classification: '电子' },
    { serialNumber: 7, itemNumber: 'WPBH007', itemName: '高强度钢材', specification: 'ST-7000-STRONG', unit: '吨', category: '原材料', classification: '金属' },
    { serialNumber: 8, itemNumber: 'WPBH008', itemName: '精密轴承', specification: 'BB-8000-PRECISE', unit: '个', category: '半成品', classification: '金属' },
    { serialNumber: 9, itemNumber: 'WPBH009', itemName: '电路板', specification: 'PC-9000-CIRCUIT', unit: '块', category: '半成品', classification: '电子' },
    { serialNumber: 10, itemNumber: 'WPBH010', itemName: '成品机器', specification: 'MC-10000-FINAL', unit: '台', category: '成品', classification: '电子' }
  ]

  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  const total = mockItems.length
  totalItems.value = total

  // 根据搜索条件过滤数据
  let filteredItems = mockItems.filter(item => {
    const keyword = itemSearchForm.keyword.toLowerCase()
    const category = itemSearchForm.category
    const classification = itemSearchForm.classification
    const inventoryStatus = itemSearchForm.inventoryStatus

    // 关键词搜索
    if (keyword && !item.itemNumber.toLowerCase().includes(keyword) && 
        !item.itemName.toLowerCase().includes(keyword) && 
        !item.specification.toLowerCase().includes(keyword)) {
      return false
    }

    // 类别筛选
    if (category && item.category !== category) {
      return false
    }

    // 分类筛选
    if (classification && item.classification !== classification) {
      return false
    }

    return true
  })

  // 分页
  itemList.value = filteredItems.slice(start, end)
}

const handleItemSelectionChange = (selection) => {
  selectedItems.value = selection
}

const handleItemCurrentChange = (currentRow) => {
  selectedItemId.value = currentRow ? currentRow.itemNumber : ''
}

const handleRadioChange = (row) => {
  selectedItemId.value = row.itemNumber
}

const handleSizeChange = (val) => {
  pageSize.value = val
  searchItems()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  searchItems()
}

const confirmItemSelection = () => {
  if (!selectedItemId.value) {
    ElMessage.warning('请选择一个物品')
    return
  }
  
  const selectedItem = itemList.value.find(item => item.itemNumber === selectedItemId.value)
  if (!selectedItem) {
    ElMessage.warning('未找到选择的物品')
    return
  }

  bomForm.finishedProductName = selectedItem.itemName
  bomForm.finishedProductType = selectedItem.category
  
  closeItemSelector()
  ElMessage.success('物品选择成功')
}

// BOM配件选择对话框相关方法
const openBomComponentSelector = () => {
  bomComponentSelectorVisible.value = true
  searchBomComponents() // 打开对话框时自动搜索
}

const closeBomComponentSelector = () => {
  bomComponentSelectorVisible.value = false
  selectedBomComponentItems.value = []
  bomComponentSearchForm.keyword = ''
  bomComponentSearchForm.category = ''
  bomComponentSearchForm.classification = ''
  bomComponentSearchForm.inventoryStatus = ''
  bomComponentSelectedItemId.value = '' // 关闭时重置选中项
}

const searchBomComponents = () => {
  // 模拟搜索逻辑
  bomComponentCurrentPage.value = 1
  fetchBomComponents()
}

const resetBomComponentSearch = () => {
  bomComponentSearchForm.keyword = ''
  bomComponentSearchForm.category = ''
  bomComponentSearchForm.classification = ''
  bomComponentSearchForm.inventoryStatus = ''
  searchBomComponents()
}

const fetchBomComponents = () => {
  // 模拟后端分页数据
  const mockItems = [
    { serialNumber: 1, itemNumber: 'WPBH001', itemName: '超能胶水', specification: 'GL-1000-TIMEBOND', unit: '个', category: '原材料', classification: '金属' },
    { serialNumber: 2, itemNumber: 'WPBH002', itemName: '神奇螺丝', specification: 'SC-2000-PROBLEMFREE', unit: '个', category: '半成品', classification: '塑料' },
    { serialNumber: 3, itemNumber: 'WPBH004', itemName: '无敌锤子', specification: 'HM-3000-SUCCESS', unit: '个', category: '成品', classification: '木材' },
    { serialNumber: 4, itemNumber: 'WPBH005', itemName: '隐形电线', specification: 'WI-4000-INVISIBLE', unit: '条', category: '原材料', classification: '金属' },
    { serialNumber: 5, itemNumber: 'WPBH003', itemName: '懒人胶带', specification: 'TA-5000-ONESTRIP', unit: '条', category: '半成品', classification: '塑料' },
    { serialNumber: 6, itemNumber: 'WPBH006', itemName: '智能传感器', specification: 'SS-6000-SMART', unit: '个', category: '成品', classification: '电子' },
    { serialNumber: 7, itemNumber: 'WPBH007', itemName: '高强度钢材', specification: 'ST-7000-STRONG', unit: '吨', category: '原材料', classification: '金属' },
    { serialNumber: 8, itemNumber: 'WPBH008', itemName: '精密轴承', specification: 'BB-8000-PRECISE', unit: '个', category: '半成品', classification: '金属' },
    { serialNumber: 9, itemNumber: 'WPBH009', itemName: '电路板', specification: 'PC-9000-CIRCUIT', unit: '块', category: '半成品', classification: '电子' },
    { serialNumber: 10, itemNumber: 'WPBH010', itemName: '成品机器', specification: 'MC-10000-FINAL', unit: '台', category: '成品', classification: '电子' }
  ]

  const start = (bomComponentCurrentPage.value - 1) * bomComponentPageSize.value
  const end = start + bomComponentPageSize.value
  const total = mockItems.length
  totalBomComponentItems.value = total

  // 根据搜索条件过滤数据
  let filteredItems = mockItems.filter(item => {
    const keyword = bomComponentSearchForm.keyword.toLowerCase()
    const category = bomComponentSearchForm.category
    const classification = bomComponentSearchForm.classification
    const inventoryStatus = bomComponentSearchForm.inventoryStatus

    // 关键词搜索
    if (keyword && !item.itemNumber.toLowerCase().includes(keyword) && 
        !item.itemName.toLowerCase().includes(keyword) && 
        !item.specification.toLowerCase().includes(keyword)) {
      return false
    }

    // 类别筛选
    if (category && item.category !== category) {
      return false
    }

    // 分类筛选
    if (classification && item.classification !== classification) {
      return false
    }

    return true
  })

  // 分页
  bomComponentItemList.value = filteredItems.slice(start, end)
}

const handleBomComponentItemSelectionChange = (selection) => {
  selectedBomComponentItems.value = selection
}

const handleBomComponentCurrentChange = (val) => {
  bomComponentCurrentPage.value = val
  searchBomComponents()
}

const handleBomComponentSizeChange = (val) => {
  bomComponentPageSize.value = val
  searchBomComponents()
}

const confirmBomComponentSelection = () => {
  if (selectedBomComponentItems.value.length === 0) {
    ElMessage.warning('请选择BOM配件')
    return
  }
  
  // 将选中的BOM配件添加到bomComponents数组中
  selectedBomComponentItems.value.forEach(selectedItem => {
    // 检查是否已经存在相同的物品
    const existingItem = bomComponents.value.find(item => item.itemNumber === selectedItem.itemNumber)
    if (!existingItem) {
      bomComponents.value.push({
        serialNumber: bomComponents.value.length + 1,
        itemNumber: selectedItem.itemNumber,
        itemName: selectedItem.itemName,
        specification: selectedItem.specification,
        unit: selectedItem.unit,
        brand: selectedItem.classification, // 使用分类作为品牌
        quantity: 1, // 默认数量
        lossRate: 0 // 默认损耗率
      })
    }
  })
  
  // 重新编号
  bomComponents.value.forEach((item, index) => {
    item.serialNumber = index + 1
  })
  
  closeBomComponentSelector()
  ElMessage.success(`成功添加 ${selectedBomComponentItems.value.length} 个BOM配件`)
}

// 工艺流程选择对话框相关方法
const openProcessFlowSelector = () => {
  processFlowSelectorVisible.value = true
  searchProcessFlows() // 打开对话框时自动搜索
}

const closeProcessFlowSelector = () => {
  processFlowSelectorVisible.value = false
  selectedProcessFlowItems.value = []
  processFlowSearchForm.keyword = ''
  processFlowSearchForm.processType = ''
  processFlowSearchForm.status = ''
  processFlowSelectedItemId.value = '' // 关闭时重置选中项
}

const searchProcessFlows = () => {
  // 模拟搜索逻辑
  processFlowCurrentPage.value = 1
  fetchProcessFlows()
}

const resetProcessFlowSearch = () => {
  processFlowSearchForm.keyword = ''
  processFlowSearchForm.processType = ''
  processFlowSearchForm.status = ''
  searchProcessFlows()
}

const fetchProcessFlows = () => {
  // 模拟后端分页数据
  const mockItems = [
    { serialNumber: 1, processFlowNumber: '7820864', processFlowName: '新产品工序流程', processCount: 5 },
    { serialNumber: 2, processFlowNumber: '5786931', processFlowName: '新产品工序流程', processCount: 4 },
    { serialNumber: 3, processFlowNumber: '8518691', processFlowName: '新产品工序流程', processCount: 6 },
    { serialNumber: 4, processFlowNumber: '1234567', processFlowName: '新产品工序流程', processCount: 5 },
    { serialNumber: 5, processFlowNumber: '2345678', processFlowName: '新产品工序流程', processCount: 4 },
    { serialNumber: 6, processFlowNumber: '3456789', processFlowName: '新产品工序流程', processCount: 6 },
    { serialNumber: 7, processFlowNumber: '4567890', processFlowName: '新产品工序流程', processCount: 5 },
    { serialNumber: 8, processFlowNumber: '5678901', processFlowName: '新产品工序流程', processCount: 4 },
    { serialNumber: 9, processFlowNumber: '6789012', processFlowName: '新产品工序流程', processCount: 6 },
    { serialNumber: 10, processFlowNumber: '7890123', processFlowName: '新产品工序流程', processCount: 5 }
  ]

  const start = (processFlowCurrentPage.value - 1) * processFlowPageSize.value
  const end = start + processFlowPageSize.value
  const total = mockItems.length
  totalProcessFlowItems.value = total

  // 根据搜索条件过滤数据
  let filteredItems = mockItems.filter(item => {
    const keyword = processFlowSearchForm.keyword.toLowerCase()
    const processType = processFlowSearchForm.processType
    const status = processFlowSearchForm.status

    // 关键词搜索
    if (keyword && !item.processFlowNumber.toLowerCase().includes(keyword) && 
        !item.processFlowName.toLowerCase().includes(keyword)) {
      return false
    }

    // 工艺类型筛选
    if (processType && !item.processFlowName.includes(processType)) {
      return false
    }

    return true
  })

  // 分页
  processFlowList.value = filteredItems.slice(start, end)
}

const handleProcessFlowItemSelectionChange = (selection) => {
  selectedProcessFlowItems.value = selection
}

const handleProcessFlowCurrentChange = (val) => {
  processFlowCurrentPage.value = val
  searchProcessFlows()
}

const handleProcessFlowSizeChange = (val) => {
  processFlowPageSize.value = val
  searchProcessFlows()
}

const confirmProcessFlowSelection = () => {
  if (selectedProcessFlowItems.value.length === 0) {
    ElMessage.warning('请选择工艺流程')
    return
  }
  
  // 将选中的工艺流程添加到processFlows数组中
  selectedProcessFlowItems.value.forEach(selectedItem => {
    // 检查是否已经存在相同的工艺流程
    const existingItem = processFlows.value.find(item => item.processFlowNumber === selectedItem.processFlowNumber)
    if (!existingItem) {
      processFlows.value.push({
        serialNumber: processFlows.value.length + 1,
        processCode: selectedItem.processFlowNumber, // 使用工艺流程编号作为工序编码
        processName: selectedItem.processFlowName,
        processingOrder: 1, // 默认加工顺序
        processFlow: selectedItem.processFlowName, // 工艺流程名称
        personInCharge: '', // 默认负责人
        department: '', // 默认部门
        unitWorkload: '', // 默认单位工作量
        remarks: '' // 默认备注
      })
    }
  })
  
  // 重新编号
  processFlows.value.forEach((item, index) => {
    item.serialNumber = index + 1
  })
  
  closeProcessFlowSelector()
  ElMessage.success(`成功添加 ${selectedProcessFlowItems.value.length} 个工艺流程`)
}

// 提交表单
const submitForm = async () => {
  try {
    await bomFormRef.value.validate()
    
    // 验证BOM配件
    if (bomComponents.value.length === 0) {
      ElMessage.warning('请至少添加一个BOM配件')
      return
    }
    
    // 验证工艺流程
    if (processFlows.value.length === 0) {
      ElMessage.warning('请至少添加一个工艺流程')
      return
    }
    
    // 这里添加提交逻辑
    ElMessage.success('保存成功')
    // 保存成功后返回列表页
    setTimeout(() => {
      router.go(-1)
    }, 1500)
  } catch (error) {
    ElMessage.error('请检查表单填写')
  }
}

// 重置表单
const resetForm = () => {
  bomFormRef.value.resetFields()
  bomComponents.value = []
  processFlows.value = []
  attachments.value = []
  fileList.value = []
  selectedBomComponents.value = []
  selectedProcessFlows.value = []
}
</script>

<style scoped>
.add-bom-page {
  background-color: #f5f5f5;
  height: 100%; /* 占满父容器高度 */
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 禁止整体滚动 */
}

.page-header {
  flex-shrink: 0; /* 不收缩 */
  margin-bottom: 20px;
  padding: 16px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 可滚动的内容区域 */
.scrollable-content {
  flex: 1; /* 占满剩余空间 */
  overflow-y: auto; /* 只允许垂直滚动 */
  overflow-x: hidden; /* 禁止水平滚动 */
  padding-right: 4px; /* 为滚动条留出空间 */
}

/* 自定义滚动条样式 */
.scrollable-content::-webkit-scrollbar {
  width: 8px;
}

.scrollable-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.scrollable-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.scrollable-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-button {
  font-size: 16px;
  color: #606266;
  padding: 0;
}

.back-button:hover {
  color: #409eff;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.form-container {
  margin-bottom: 20px;
}

.form-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  background: #fafafa;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.form-content {
  padding: 24px;
}

.bom-form {
  width: 100%;
}

.bom-number-input {
  width: 100%;
}

.full-width {
  width: 100%;
}

.item-selector-icon {
  cursor: pointer;
  color: #409eff;
  font-size: 18px;
}

.item-selector-icon:hover {
  color: #66b1ff;
}

/* 必填字段的红色星号样式 */
:deep(.el-form-item__label::before) {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

/* 表单行间距 */
.el-form-item {
  margin-bottom: 20px;
}

/* 复选框样式调整 */
:deep(.el-checkbox) {
  margin-left: 0;
}

/* 操作按钮区域 */
.action-buttons {
  text-align: center;
  padding: 20px 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-buttons .el-button {
  margin: 0 10px;
  min-width: 100px;
}

/* 卡片头部操作按钮样式 */
.card-actions {
  display: flex;
  gap: 12px;
}

.card-actions .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 表格内容区域 */
.table-content {
  padding: 20px;
}

/* 表格样式 */
.bom-table,
.process-table {
  width: 100%;
}

/* 附件内容区域 */
.attachment-content {
  padding: 20px;
}

.attachment-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

/* 附件显示区域 */
.attachment-display {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  min-height: 200px;
  background: #fafafa;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.attachment-item {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
}

.attachment-info {
  margin-bottom: 8px;
}

.file-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.file-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
  font-size: 12px;
  color: #909399;
}

.attachment-actions {
  display: flex;
  gap: 8px;
  border-top: 1px solid #f0f0f0;
  padding-top: 8px;
}

.attachment-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f78989;
}

/* 空附件提示 */
.empty-attachments {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 8px;
  color: #c0c4cc;
}

/* 上传区域 */
.upload-zone {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  min-height: 200px;
}

.upload-area {
  width: 100%;
  height: 100%;
}

.upload-area :deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  transition: all 0.3s;
}

.upload-area :deep(.el-upload-dragger:hover) {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
}

/* 物品选择对话框样式 */
.item-selector-dialog {
  /* Add specific styles if needed */
}

/* BOM配件选择对话框样式 */
.bom-component-selector-dialog {
  /* Add specific styles if needed */
}

/* 工艺流程选择对话框样式 */
.process-flow-selector-dialog {
  /* Add specific styles if needed */
}

.search-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.search-section .el-row {
  align-items: center;
  margin-bottom: 15px;
}

.search-section .el-col {
  display: flex;
  align-items: center;
}

.search-section .el-input,
.search-section .el-select {
  width: 100%;
  margin-right: 10px;
}

.search-section .el-button {
  min-width: 80px;
}

.table-section {
  margin-bottom: 20px;
}

.item-table {
  width: 100%;
}

.bom-component-item-table {
  width: 100%;
}

.process-flow-item-table {
  width: 100%;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
}

.dialog-footer {
  text-align: right;
}

/* 全局操作按钮 */
.global-actions {
  flex-shrink: 0; /* 不收缩 */
  text-align: center;
  padding: 20px 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

.global-actions .el-button {
  margin: 0 10px;
  min-width: 120px;
}

.close-btn {
  background: white;
  border: 1px solid #409eff;
  color: #409eff;
}

.close-btn:hover {
  background: #f0f9ff;
  border-color: #66b1ff;
  color: #66b1ff;
}

.confirm-btn {
  background: #409eff;
  border-color: #409eff;
}

.confirm-btn:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-bom-page {
    padding: 16px;
  }
  
  .page-header {
    padding: 12px 16px;
  }
  
  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .el-col {
    width: 100% !important;
  }
  
  .form-content {
    padding: 16px;
  }
  
  .table-content {
    padding: 16px;
  }
  
  .attachment-content {
    padding: 16px;
  }
  
  .attachment-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .global-actions .el-button {
    margin: 5px;
    width: 100%;
    max-width: 200px;
  }
  
  .card-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .card-actions .el-button {
    width: 100%;
  }
}
</style>
